package com.sky.Task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    OrderMapper mapper;

    //秒、分钟、小时、日、月、周、年(可选)
    @Scheduled(cron = "* * 1 * * ? ")        //定时任务
    //处理未支付的超时订单 ，每分钟查一次
    public void demo() {
        log.info("处理未支付的超市订单");
        //根据状态和支付状态查询
        List<Orders> list = mapper.selectTimeOut(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));

        //查到后修改状态
        for (Orders orders : list) {
            orders.setStatus(Orders.COMPLETED);
            orders.setCancelTime(LocalDateTime.now());
            orders.setCancelReason(MessageConstant.ORDER_LATER);
            mapper.update(orders);
            System.out.println("清理了未支付的订单" + orders.getNumber());
        }
    }

    //处理派送中的订单设置为已完成，在每天凌晨两点
    @Scheduled(cron = "10 * * * * ? ")        //定时任务
    public void demo2() {
        log.info("处理派送中的订单设置为已完成");

        List<Orders> list = mapper.selectTimeOut(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusMinutes(-60));

        //查到后修改状态
        for (Orders orders : list) {
            orders.setStatus(Orders.COMPLETED);
            mapper.update(orders);
            System.out.println("清理了派送中的的订单" + orders.getNumber());

        }
    }

    //自动接单
    @Scheduled(cron = "10 * * * * ? ")        //定时任务
    public void demo3() {
        log.info("自动接单");

        List<Orders> list = mapper.selectTimeOut(Orders.TO_BE_CONFIRMED, LocalDateTime.now().plusSeconds(20));

        //查到后修改状态
        for (Orders orders : list) {
            orders.setStatus(Orders.CONFIRMED);
            mapper.update(orders);
            System.out.println("自动接到了订单" + orders.getNumber());

        }
    }

    //自动派送
    @Scheduled(cron = "5 * * * * ? ")
    public void demo4() {
        log.info("自动派送");
        List<Orders> list = mapper.selectTimeOut(Orders.CONFIRMED, LocalDateTime.now().plusSeconds(10));
        for (Orders orders : list) {
            orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
            mapper.update(orders);
            System.out.println("已经派送了一单" + orders.getNumber());
        }

    }




}

